package com.hmkj.quartz.controller;

import com.hmkj.common.baseMapper.GenericPo;
import com.hmkj.common.entity.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * json数据类controller 基础实现
 *
 * @author Administrator
 * @param <PK> 对象主键类型
 * @param <PO> 对象
 */
@Slf4j
public class GenericController<PK, PO extends GenericPo<PK>> {

    /**
     * api地址跟路径
     */
    public static final String BASE_URL = "/quote/";



    /**
     * 操作成功
     *
     * @return
     */
    protected <T> ResultEntity<T> ok() {
        return result(null, "success", ResultEntity.SUCCESS);
    }

    /**
     * 操作成功
     *
     * @param po 返回数据
     * @return
     */
    protected <T> ResultEntity<T> ok(String msg, T po) {
        return result(po, msg, ResultEntity.SUCCESS);
    }

    /**
     * 操作成功
     *
     * @param po 返回数据
     * @return
     */
    protected <T> ResultEntity<T> ok(T po) {
        return result(po, "success", ResultEntity.SUCCESS);
    }
    /**
     * 操作成功
     *
     * @param consumer 返回数据
     * @return
     */
    protected ResultEntity ok(Consumer<Map<String, Object>> consumer) {
        Map<String, Object> result = new HashMap<>();
        consumer.accept(result);
        return result(result, "success", ResultEntity.SUCCESS);
    }

    /**
     * 操作失败
     *
     * @return
     */
    protected <T> ResultEntity<T> fail(String msg) {
        return result(null, msg, ResultEntity.FAIL);
    }

    /**
     * 操作失败
     *
     * @return
     */
    protected <T> ResultEntity<T> fail() {
        return result(null, "fail", ResultEntity.FAIL);
    }

    /**
     * 返回消息记录
     *
     * @param resultData 返回实体(可空)
     * @param msg        返回消息
     * @param code       成功/错误
     * @return
     */
    protected <T> ResultEntity<T> result(T resultData, String msg, int code) {
        ResultEntity resultEntity = new ResultEntity();
        resultEntity.setData(resultData);
        resultEntity.setCode(code);
        resultEntity.setMessage(msg);
        return resultEntity;
    }


    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

}
